package com.service;

import com.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisServiceImpl implements IRedisService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加一些（实际项目从数据库查询出来）
     */
    @Override
    public void addMapPoint() {

            //添加测试数据
        BoundGeoOperations rt=redisTemplate.boundGeoOps("p");
        rt.add(new Point(118.803805, 32.060168),"南京");
        rt.add(new Point(116.397039, 39.9077), "北京");
        rt.add(new Point(113, 28.21), "长沙");
        rt.add(new Point(113.16, 27.83), "株洲");

        //求两点距离：单位千米km
        Distance distance=rt.distance("长沙","株洲", Metrics.KILOMETERS);
        System.out.println(distance.getValue());


        //求附近的人：以株洲为中心，方圆50公里的人
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiuArgs=RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        geoRadiuArgs.includeDistance().includeCoordinates().sortAscending().limit(4);
        GeoResults<RedisGeoCommands.GeoLocation> results=rt.radius("株洲",new Distance(1500,Metrics.KILOMETERS),geoRadiuArgs);

        for (GeoResult<RedisGeoCommands.GeoLocation> r:results){
            RedisGeoCommands.GeoLocation location=r.getContent();
            String name=(String)location.getName();
            Distance d=r.getDistance();
            System.out.println(name+"\t"+d.getValue());
        }

    }
}
